package com.hmdp.mq.consumer;

import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.IVoucherOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class VoucherOrderConsumer {

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @RabbitListener(queues = "seckill.order.queue")
    public void handleVoucherOrder(VoucherOrder voucherOrder, Channel channel, Message message) throws IOException {
        try {
            // 处理订单逻辑
            voucherOrderService.createVoucherOrder(voucherOrder);
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("优惠券下单成功！");
        } catch (Exception e) {
            log.error("订单处理失败，消息重回队列，原因：{}", e.getMessage());
            // 消息重新入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
